package cn.jdy.plugins.service;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.SQLQuery;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Service;

import cn.jdy.framework.db.hibernate.BaseDao;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.plugins.entity.ExamQuestions;
import cn.jdy.plugins.entity.Live;

/**
 * @desc   试题实体操作
 * @author ningqian
 * @date   2016-7-5
 */
@Service
public class ExamQuestionsService extends BaseDao<ExamQuestions>{

	/**
	 * 按条件查询
	 * @param examQuestions
	 * @return
	 */
	public List<ExamQuestions> query(ExamQuestions examQuestions, String... date) {
		if(null == examQuestions) return super.findAll();
		if(examQuestions.getiDisplayLength() > 0){
		  return super.find(createFilter(examQuestions, date),examQuestions.getiDisplayStart(),examQuestions.getiDisplayLength());
		}
		return super.find(createFilter(examQuestions, date));
	}

	public Long count(ExamQuestions examQuestions, String... date) {
		return super.count(createFilter(examQuestions, date));
	}
	
	/**
	 * 拼装条件(所属项目、题干、创建时间)
	 * @param evaluationProject
	 * @param date
	 * @return
	 */
	private DetachedCriteria createFilter(ExamQuestions examQuestions, String... date) {
	  DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
	  
	  if(null != examQuestions.getProjectId()){
		  dc.add(Restrictions.eq("projectId", examQuestions.getProjectId()));
	  }
	  
	  if(!StringUtil.isNullOrEmpty(examQuestions.getQuestionName())){
		  dc.add(Restrictions.like("questionName", examQuestions.getQuestionName().trim(), MatchMode.ANYWHERE));
	  }
	  
	  if(date.length>0 && !StringUtil.isNullOrEmpty(date[0]) && !StringUtil.isNullOrEmpty(date[1])){
	    dc.add(Restrictions.between("insertTime", date[0],date[1]));
	  }
	  
	  dc.addOrder(Order.asc("sort"));
		return dc;
	}
	
	/**
	 * 获取试题sort最大值
	 * @return maxSort
	 */
	public Integer getMaxSort(){
		List<ExamQuestions> list = new ArrayList<ExamQuestions>();
		int maxSort=0;
		try {
			DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
			dc.addOrder(Order.desc("sort"));
			list = super.find(dc);
			if(list.size()>0){
				maxSort=list.get(0).getSort();
			}
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return maxSort;
	}
	
	  /**
	   * web police
	   *  统计 投票  图表格式 date1{名字，名字}，date1{统计总量，统计总量}
	   * @return
	   */
	  public HashMap<String,Object> evaluationRecord(Long id) {
	    try {
	    	  String sql = "select o.optionName as name,count(e.id  ) as zs from ExamOptions o  LEFT JOIN EvaluationRecord  e  on  o.id=e.optionsId  where o.questionId=?   group by o.optionName order by o.sort desc ";
	    	      SQLQuery sqlQuery = em().createSQLQuery(sql);
	    	      sqlQuery.setParameter(0,id);
	    	 // 将查询寻结果转换为Map格式，解决多表查询或零散字段查询 映射取值问题
		      sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		      List<Map<String,Object>>  list=  sqlQuery.list();
		      LinkedHashMap<String,Object> ma=new  LinkedHashMap<String,Object>();
		      List list2=new ArrayList<>();
		      List list3=new ArrayList<>();
		      for (int i = 0; i < list.size(); i++) {
		    	  Map<String,Object> p=list.get(i);
		    	 
		    	  list2.add(p.get("name"));
		    	  list3.add(p.get("zs"));
		    	 
			}
		      ma.put("name" ,list2);
		      ma.put("zs", list3);
		      return  ma;
		    } catch (Exception e) {
		      BaseLog.e(this.getClass(), "搜索模糊查询异常！", e);
		    }
		    return null;
		  }
	  

	  /**
	   * web police
	   *  统计 投票  列表显示格式 date1{[名字，统计数据]} 
	   * @return
	   */
	  public List<LinkedHashMap<String,Object>> evaluationListRecord(Long id) {
	    try {
	    	  String sql = "select o.optionName as name,count(e.id  ) as zs from ExamOptions o  LEFT JOIN EvaluationRecord  e  on  o.id=e.optionsId  where o.questionId=?   group by o.optionName order by  zs  desc ";
	    	      SQLQuery sqlQuery = em().createSQLQuery(sql);
	    	      sqlQuery.setParameter(0,id);
	    	 // 将查询寻结果转换为Map格式，解决多表查询或零散字段查询 映射取值问题
		      sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		      List<LinkedHashMap<String,Object>>  list=  sqlQuery.list();
		    
		 
		      return  list;
		    } catch (Exception e) {
		      BaseLog.e(this.getClass(), "搜索模糊查询异常！", e);
		    }
		    return null;
		  }
	



/**
 * web police
 *  查看数据这个人是否投票  
 * @return
 */
public long isEvaluationRecord(Long liveId,String userId) {
  try {
  	  String sql = "select userId,count(id)as zs from EvaluationRecord where liveId=? and userId=? ";
  	      SQLQuery sqlQuery = em().createSQLQuery(sql);
  	      sqlQuery.setParameter(0,liveId);
  	    sqlQuery.setParameter(1,userId);
  	 // 将查询寻结果转换为Map格式，解决多表查询或零散字段查询 映射取值问题
	      sqlQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
	    Map<String,Object> m  =(Map<String, Object>) sqlQuery.list().get(0);
		  Long cnt = ((BigInteger) m.get("zs")).longValue();
	    return   cnt;
	    } catch (Exception e) {
	      BaseLog.e(this.getClass(), "搜索模糊查询异常！", e);
	    }
	    return 0;
	  }

}